package com.industry.system.service;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Sets;
import com.industry.framework.common.page.PageConverter;
import com.industry.framework.common.page.PageQuery;
import com.industry.framework.common.page.TableDataInfo;
import com.industry.framework.file.local.LocalFileClient;
import com.industry.system.controller.vo.MenuTreeRespVO;
import com.industry.system.controller.vo.RoleMenuVo;
import com.industry.system.controller.vo.RoleVo;
import com.industry.system.dal.dataobject.SystemMenu;
import com.industry.system.dal.dataobject.SystemRole;
import com.industry.system.dal.dataobject.SystemRoleMenu;
import com.industry.system.dal.db.SystemMenuMapper;
import com.industry.system.dal.db.SystemRoleMapper;
import com.industry.system.dal.db.SystemRoleMenuMapper;
import com.industry.system.satoken.StpContextHelper;
import com.industry.system.utils.SystemMenuUtils;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author nbZhuozh
 * @Date 2025-02-13  21:07
 **/
@Service
public class SystemRoleService {

    private static final Logger log = LoggerFactory.getLogger(SystemRoleService.class);
    @Resource
    private SystemRoleMapper systemRoleMapper;

    @Resource
    private SystemRoleMenuMapper roleMenuMapper;

    @Resource
    private SystemMenuMapper systemMenuMapper;

    //查询角色列表
    public TableDataInfo<RoleVo> queryRoleList(PageQuery pageQuery) {
        Long loginId = Long.valueOf(StpUtil.getTokenInfo().getLoginId().toString());
        //超管可以获取所有角色
        if (loginId == 1L) {
            Page<SystemRole> systemRolePage = systemRoleMapper.selectPage(pageQuery.build(), new QueryWrapper<>());
            return TableDataInfo.build(PageConverter.convert(systemRolePage, RoleVo.class));
        }
        //其它根据用户的所属部门查询角色 或 公共角色
        String deptId = StpContextHelper.getUserInfo().getDeptId();

        LambdaQueryWrapper<SystemRole> queryWrapper = Wrappers.lambdaQuery(SystemRole.class)
                .eq(SystemRole::getDeptId, deptId).or().isNull(SystemRole::getDeptId);
        Page<SystemRole> systemRolePage = systemRoleMapper.selectPage(pageQuery.build(), queryWrapper);
        return TableDataInfo.build(PageConverter.convert(systemRolePage, RoleVo.class));
    }


    //根据id 查询角色
    public SystemRole queryRoleById(Long roleId) {
        if (null != roleId) {
            return systemRoleMapper.selectById(roleId);
        }
        return new SystemRole();
    }

    //新增角色
    @Transactional(rollbackFor = Exception.class)
    public boolean insert(RoleMenuVo roleMenuVo) {
        systemRoleMapper.insert(roleMenuVo);
        if(!CollectionUtils.isEmpty(roleMenuVo.getMenuIds())){
            List<SystemRoleMenu> ls = new ArrayList<>();
            roleMenuVo.getMenuIds().forEach(i->{
                SystemRoleMenu systemRoleMenu = new SystemRoleMenu();
                systemRoleMenu.setRoleId(roleMenuVo.getId());
                systemRoleMenu.setMenuId(i);
                ls.add(systemRoleMenu);
            });
            roleMenuMapper.insert(ls);
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public void modify(RoleMenuVo roleMenuVo) {
        final String roleId = roleMenuVo.getId();
        if (StringUtils.isEmpty(roleId)) {
            log.warn("Empty roleId in modify request");
            return;
        }
        // 获取输入数据
        final Set<String> currentMenuIds = new HashSet<>(roleMenuVo.getMenuIds());
        // 根据当前角色查询数据库现有数据
        final Set<String> databaseMenuIds = roleMenuMapper.selectList(
                Wrappers.<SystemRoleMenu>lambdaQuery()
                        .select(SystemRoleMenu::getMenuId)
                        .eq(SystemRoleMenu::getRoleId, roleId)
        ).stream().map(SystemRoleMenu::getMenuId).collect(Collectors.toSet());
        final Set<String> addList = Sets.difference(currentMenuIds, databaseMenuIds);
        final Set<String> delList = Sets.difference(databaseMenuIds, currentMenuIds);
        //del
        if(!CollectionUtils.isEmpty(delList)){
            roleMenuMapper.delete(Wrappers.<SystemRoleMenu>lambdaQuery()
                    .select(SystemRoleMenu::getRoleId).in(SystemRoleMenu::getMenuId,delList));
        }
        //insert
        if(!CollectionUtils.isEmpty(addList)){
            List<SystemRoleMenu> collect = addList.stream().map(menuId -> {
                SystemRoleMenu sr = new SystemRoleMenu();
                sr.setRoleId(roleId);
                sr.setMenuId(menuId);
                sr.setDelFlag("0");
                return sr;
            }).toList();
            roleMenuMapper.insert(collect);
        }

        systemRoleMapper.updateById(roleMenuVo);
    }

    //查询角色关联菜单
    public List<SystemMenu> getRoleMenuInfosByRoleId(String roleId){
        List<SystemRoleMenu> systemRoleMenus = roleMenuMapper.selectList(Wrappers.lambdaQuery(SystemRoleMenu.class)
                .eq(SystemRoleMenu::getRoleId, roleId));
        if(CollectionUtils.isEmpty(systemRoleMenus)){
            return new ArrayList<>();
        }
        Set<String> menuIds = systemRoleMenus.stream().map(SystemRoleMenu::getMenuId).collect(Collectors.toSet());
        List<SystemMenu> menus = systemMenuMapper.selectList(Wrappers.lambdaQuery(SystemMenu.class)
                .eq(SystemMenu::getStatus,0L)
                .in(SystemMenu::getId,menuIds));
        return menus;
    }


}
